package grpcservercategory

import (
	"context"
	"errors"
	"go-gin-api/app/model/category"

	grpccategory "go-gin-api/app/proto/category"
)

type CategoryServer struct {
	category category.CategoryRepository
}

func NewCategorySever (category category.CategoryRepository) grpccategory.CategoryHandler {
	return &CategoryServer{
		category:category,
	}
}

func (s *CategoryServer) Category(ctx context.Context,req *grpccategory.CategoryRequest,res *grpccategory.CategoryResponse) error {
	flag := s.category.ExistsCategoryByName(req.Name,0)
	if flag {
		return errors.New("category name 存在 不允许添加")
	}
	err := s.category.CategoryAdd(req)
	if err == nil {
		res.Res = true
	}
	return err
}

func (s *CategoryServer) CategoryDel(ctx context.Context,req *grpccategory.CategoryDelRequest,res *grpccategory.CategoryDelResponse) error {
	err := s.category.CategoryDel(req)
	if err == nil {
		res.Res = true
	}
	return err
}

func (s *CategoryServer) CategoryUpdate(ctx context.Context,req *grpccategory.CategoryUpdateRequest,res *grpccategory.CategoryUpdateResponse) error {
	flag := s.category.ExistsCategoryByName(req.Name,int(req.Id))
	if flag {
		return errors.New("category name 存在 不允许添加")
	}
	err := s.category.CategoryUpdate(req)
	if err == nil {
		res.Res = true
	}
	return err
}

func (s *CategoryServer) CategoryList(ctx context.Context,req *grpccategory.CategoryListRequest,res *grpccategory.CategoryListResponse) error {
	var (
		categoryList []*grpccategory.CategoryInfoResponse
	)
	data,err := s.category.CategoryList(req)
	if err != nil {
		return errors.New("category 获取失败")
	}
	if len(data) > 0 {
		for _,item := range data   {
			row := &grpccategory.CategoryInfoResponse{
				Id:        int32(item.ID),
				Name:      item.Name,
				Status:    int32(item.Status),
				CreatedAt: item.CreatedAt.Format(""),
			}
			categoryList = append(categoryList,row)
		}
	}
	res.List = categoryList
	return  nil
}

func (s *CategoryServer) CategoryInfo(ctx context.Context,req *grpccategory.CategoryInfoRequest,res *grpccategory.CategoryInfoResponse) error {
	data,err := s.category.CategoryInfo(req)
	if err != nil {
		return errors.New("category 获取失败")
	}
	res.Pid = int32(data.Pid)
	res.Name = data.Name
	res.CreatedAt = data.CreatedAt.Format("2006-01-02 15:04:05")
	res.Id = int32(data.ID)
	return nil
}


